﻿$.extend($.fn.datagrid.methods, {
	cancelEditing:function(jq){
		var dg=jq;
		var editId = dg.data('editId');
		if (editId){
			var editIndex=dg.datagrid('getRowIndex',editId);
			if(editIndex){
				dg.datagrid('cancelEdit',editIndex);
			}
		}
	},
	beginEditing:function(jq,param){
		var dg=jq;
		var idField=dg.datagrid('options').idField;
		var rowid=param[idField];
		if(!rowid){
			alert("row没有主键,可能原因,没有定义idField");
		}
		var rowIndex=dg.datagrid('getRowIndex',rowid);
		if(dg.data('editId')!=rowid){
    		if(dg.datagrid('endEditing')){
    			//开始编辑
    			dg.datagrid('selectRow', rowIndex).datagrid('beginEdit', rowIndex);
				dg.data('editId',rowid);
    		}
    	}
	},
	endEditing:function(jq){
		var dg=jq;
		var editId = dg.data('editId');
		var editIndex=dg.datagrid('getRowIndex',editId);
		if (editIndex == undefined){return true;}
		if (dg.datagrid('validateRow', editIndex)){
			dg.datagrid('endEdit', editIndex);
			dg.removeData('editId');
			dg.datagrid('afterEditing');
			return true;
		} else {
			return false;
		}
	},
	afterEditing:function(jq,param){
		return jq.each(function(){
			var dg=jq;
			if(dg.datagrid('options').afterEditing){
				dg.datagrid('options').afterEditing();
			}
		});
	},
	append:function(jq,param){
		return jq.each(function(){
			var dg=jq;
			if(dg.datagrid('endEditing')){
				var length=dg.datagrid('getRows').length;
				var idField=dg.datagrid('options').idField;
				dg.datagrid('appendRow',param);//新增一行
				dg.data('editId',param[idField]);
				dg.datagrid('selectRow', length).datagrid('beginEdit',length);//编辑新增行
			}
		});
	},
	editRow:function(jq,param){
		var dg=jq;
		var selectRows=dg.datagrid('getSelections');
		if(selectRows.length>0){
			dg.datagrid('beginEditing',selectRows[0]);
		}else{
			$.messager.alert("提示", "请选择一条数据！");
		}
	},
	remove:function(jq){
		var dg=jq;
		var selectRow=dg.datagrid('getSelections');
		if(selectRow.length>0){
			$.each(selectRow,function(i,v){
				var deleteIndex=dg.datagrid('getRowIndex',v);
				dg.datagrid('deleteRow', deleteIndex);
			});
		}
	},
	getEditIndex:function(jq){
		var dg=jq;
		var editIndex=undefined;
		var editId = dg.data('editId');
		if (editId){
			editIndex=dg.datagrid('getRowIndex',editId);
		}
		return editIndex;
	},
	getSearchParam:function(jq,param){
		var dg=jq;
		var searchbar=dg.datagrid('options').toolbar;
		//var table=dg.datagrid('options').table;
		//var sqlname=dg.datagrid('options').sqlname;
		var searchForm=$(searchbar+" form");
		var searchParam=searchForm.serializeObject();
		if(dg.searchParamOperator){
			$.each(dg.searchParamOperator,function(i,v){
				if(searchParam[i]){
					if(v=="startWith"){
						searchParam[i]=searchParam[i]+"%";
					}else if(v=="contain"){
						searchParam[i]="%"+searchParam[i]+"%";
					}
				}
			});
		}
		$.extend(searchParam,dg.gridParam,dg.loadParam);
		return searchParam;
	},
	load:function(jq,param){
		var dg=jq;
		dg.datagrid("loading");
		var searchbar=dg.datagrid('options').toolbar;
		//var table=dg.datagrid('options').table;
		//var sqlname=dg.datagrid('options').sqlname;
		var searchForm=$(searchbar+" form");
		var searchParam=searchForm.serializeObject();
		if(dg.searchParamOperator){
			$.each(dg.searchParamOperator,function(i,v){
				if(searchParam[i]){
					if(v=="startWith"){
						searchParam[i]=searchParam[i]+"%";
					}else if(v=="contain"){
						searchParam[i]="%"+searchParam[i]+"%";
					}
				}
			});
		}
		//console.log(searchParam);
		//console.log(dg.gridParam);
		//console.log(dg.loadParam);
		$.extend(searchParam,dg.gridParam,dg.loadParam);
		$.post(dg.datagrid('options').loadurl,searchParam,function(result){
//			var idField=dg.datagrid('options').idField;
//			console.log(idField);
//			$.each(result.rows,function(i,row){
//				console.log(new String(row[idField]));
//				row[idField]="d"+row[idField].toString();
//			});
			dg.datagrid("loadData",result.rows||[]);
			if(dg.pager){
				dg.datagrid('getPager').pagination('refresh',{
					total: result.total,
					pageNumber: dg.gridParam.pageNumber
				});
			}
			dg.datagrid("loaded");
		});
		
	},accept:function(jq,param){
		var dg=jq;
		//var table=dg.datagrid('options').table;
		//var sqlname=dg.datagrid('options').sqlname;
		if (dg.datagrid('endEditing')){
			var rows = dg.datagrid('getChanges');
			if (rows.length == 0) {
				$.messager.alert("提示", "没有需要提交的数据！");
				return;
			}
			var insertedRows = dg.datagrid('getChanges','inserted');
			var deletedRows  = dg.datagrid('getChanges','deleted');
			var updatedRows  = dg.datagrid('getChanges','updated');
			var params = {};
			if(insertedRows.length>0){
				params.insertedRows=insertedRows;
			}
			if(updatedRows.length>0){
				params.updatedRows=updatedRows;
			}
			if(deletedRows.length>0){
				var idArr=new Array();
				var idField=dg.datagrid('options').idField;
				$.each(deletedRows, function(i, row){
					idArr.push(row[idField]);
				});
				params.deletedRowIds=idArr;
			}
			params.gridParam=dg.gridParam;
			console.log(dg.gridParam);
			var saveurl=dg.datagrid('options').saveurl;
			$.ajax({
				contentType:"application/json",
				url: saveurl,
				type:"POST",
				data:JSON.stringify(params),
				success: function(result){
					if(result.success){
						dg.datagrid('acceptChanges');
						dg.datagrid('load');
						$.messager.alert("提示", "保存成功！");
					}else{
						$.messager.alert("错误", result.message);
					}			
				}
			});
		}
	},showChanges:function(jq,param){
		var dg=jq;
		if (dg.datagrid('endEditing')){
			var changesRows=dg.datagrid('getChanges');
			var insertedRows = dg.datagrid('getChanges','inserted');
			var deletedRows = dg.datagrid('getChanges','deleted');
			var updatedRows = dg.datagrid('getChanges','updated');
			$.messager.alert("提示", changesRows.length+"条数据修改<br>新增"+insertedRows.length+"条,删除"+deletedRows.length+"条，更新"+updatedRows.length+"条");
		}else{
			$.messager.alert("提示", "编辑未结束！");
		}
	},getSelectedRow:function(jq,param){
		var dg=jq;
		var selectRow=dg.datagrid('getSelected');
		if(selectRow){
			return selectRow;
		}else{
			$.messager.alert("提示", "请选择一条数据");
			return undefined;
		}
	},editCell: function(jq,param){
		return jq.each(function(){
			var opts = $(this).datagrid('options');
			var fields = $(this).datagrid('getColumnFields',true).concat($(this).datagrid('getColumnFields'));
			for(var i=0; i<fields.length; i++){
				var col = $(this).datagrid('getColumnOption', fields[i]);
				col.editor1 = col.editor;
				if (fields[i] != param.field){
					col.editor = null;
				}
			}
			$(this).datagrid('beginEdit', param.index);
            var ed = $(this).datagrid('getEditor', param);
            if (ed){
                if ($(ed.target).hasClass('textbox-f')){
                    $(ed.target).textbox('textbox').focus();
                } else {
                    $(ed.target).focus();
                }
            }
			for(var i=0; i<fields.length; i++){
				var col = $(this).datagrid('getColumnOption', fields[i]);
				col.editor = col.editor1;
			}
			$(this).datagrid('afterEditing');
		});
	},enableCellEditing: function(jq){
        return jq.each(function(){
            var dg = $(this);
            var opts = dg.datagrid('options');
            opts.oldOnClickCell = opts.onClickCell;
            opts.onClickCell = function(index, field){
                if (opts.editIndex != undefined){
                    if (dg.datagrid('validateRow', opts.editIndex)){
                        dg.datagrid('endEdit', opts.editIndex);
                        opts.editIndex = undefined;
                    } else {
                        return;
                    }
                }
                dg.datagrid('selectRow', index).datagrid('editCell', {
                    index: index,
                    field: field
                });
                opts.editIndex = index;
                opts.oldOnClickCell.call(this, index, field);
            }
        });
    },autoMergeCells : function (jq, fields) {
        return jq.each(function () {
            var target = jq;
            if (!fields) {
                fields = target.datagrid("getColumnFields");
            }
            var rows = target.datagrid("getRows");
            var i = 0,
            j = 0,
            temp = {};
            
            for (i; i < rows.length; i++) {
                var row = rows[i];
                j = 0;
                for (j; j < fields.length; j++) {
                    var field = fields[j];
                    var tf = temp[field];
                    if (!tf) {
                        tf = temp[field] = {};
                        tf[row[field]] = [i];
                    } else {
                        var tfv = tf[row[field]];
                        if (tfv) {
                            tfv.push(i);
                        } else {
                            tfv = tf[row[field]] = [i];
                        }
                    }
                }
            }
            $.each(temp, function (field, colunm) {
                $.each(colunm, function () {
                    var group = this;
                    
                    if (group.length > 1) {
                        var before,
                        after,
                        megerIndex = group[0];
                        for (var i = 0; i < group.length; i++) {
                            before = group[i];
                            after = group[i + 1];
                            if (after && (after - before) == 1) {
                                continue;
                            }
                            var rowspan = before - megerIndex + 1;
                            if (rowspan > 1) {
                                target.datagrid('mergeCells', {
                                    index : megerIndex,
                                    field : field,
                                    rowspan : rowspan
                                });
                            }
                            if (after && (after - before) != 1) {
                                megerIndex = after;
                            }
                        }
                    }
                });
            });
        });
    },
    autoMergeCellAndCells : function (jq, fields) {
        return jq.each(function () {
            var target = jq;
            if (!fields) {
                fields = target.datagrid("getColumnFields");
            }
            var cfield = fields[0];
            if (!cfield) {
                return;
            }
            var rows = target.datagrid("getRows");
            var i = 0,
            j = 0,
            temp = {};
            for (i; i < rows.length; i++) {
                var row = rows[i];
                j = 0;
                var tf = temp[cfield];
                if (!tf) {
                    tf = temp[cfield] = {};
                    tf[row[cfield]] = [i];
                
                } else {
                    var tfv = tf[row[cfield]];
                    if (tfv) {
                        tfv.push(i);
                    } else {
                        tfv = tf[row[cfield]] = [i];
                        
                    }
                }
            }
            
            $.each(temp, function (field, colunm) {
                $.each(colunm, function () {
                    var group = this;
                    
                    if (group.length > 1) {
                        var before,
                        after,
                        megerIndex = group[0];
                        for (var i = 0; i < group.length; i++) {
                            before = group[i];
                            after = group[i + 1];
                            if (after && (after - before) == 1) {
                                continue;
                            }
                            var rowspan = before - megerIndex + 1;
                            if (rowspan > 1) {
                                for(var j=0;j<fields.length;j++){
                                    target.datagrid('mergeCells', {
                                        index : megerIndex,
                                        field : fields[j],
                                        rowspan : rowspan
                                   });
                                }
                            }
                            if (after && (after - before) != 1) {
                                megerIndex = after;
                            }
                        }
                    }
                });
            });
        });
    }
});
uniontrip={
		datagrid:{
			searchEdit:function (options){
				var self = this;
				if(options.showCheckbox!=undefined&&options.showCheckbox==false){
					this.columns=[[]];
				}else{
					this.columns=[[{field:'checkbox',checkbox:true}]];
				}
				this.fun={
					field:{
						formatter:function(param){
							this.field=param;
							this.comboboxFormatter=function (value,row,index){
								return self.getComoboxValue(this.field,value);
						    };
							this.combotreeFormatter=function (value,row,index){
								return self.getCombotreeValue(this.field,value);
						    };
						}
					}
				};
				this.comboboxDatas={};
				this.combotreeDatas={};
				this.getComoboxValue=function(field,value){
					var text=value;
					$.each(self.comboboxDatas[field],function(i,v){
						if(v.code_value==value){
							text= v.code_name;
							return text;
						}
					});
					return text;
				};
				this.getCombotreeValue=function(field,value){
					var text;
					$.each(self.comboboxDatas[field],function(i,v){
						if(v.id==value){
							text= v.text;
							return text;
						}
					});
					return text;
				}
				this.onSelectPage=function(pageNumber, pageSize){
					self.grid.gridParam.pageNumber=pageNumber;
					self.grid.gridParam.pageSize=pageSize;
					self.grid.datagrid("load");
				};
				
				this.onDblClickRow=function(rowIndex,rowData){
					self.grid.datagrid('beginEditing',rowData);
				};
				this.onSortColumn=function(sort, order){
					self.grid.gridParam.sort=sort;
					self.grid.gridParam.order=order;
					self.grid.datagrid("load");
				};
				this.editRow=function(){
					self.grid.datagrid('editRow');
				};
				this.accept=function(){
					self.grid.datagrid('accept');
				};
				this.cancelEditing=function(){
					self.grid.datagrid('cancelEditing');
				};
				this.endEditing=function(){
					self.grid.datagrid('endEditing');
				};
				this.rejectChanges=function(){
					self.grid.datagrid('rejectChanges');
				};
				this.remove=function(){
					self.grid.datagrid('remove');
				};
				this.load= function(e){
					self.grid.datagrid('load');
				};
				this.loadParam= function(p){
					self.grid.loadParam=p;
					self.grid.datagrid('load');
				};
				this.getSearchParam= function(){
					return self.grid.datagrid('getSearchParam');
				};
				this.getSelectedRow= function(){
					return self.grid.datagrid('getSelectedRow');
				};
				this.showChanges = function(){
					self.grid.datagrid('showChanges');
				}
				this.paginationOptions={layout:['list','sep','first','prev','sep','manual','sep','next','last','sep','refresh','info'],
						pageSize:25,
						pageList:[25,50,100],
					    onSelectPage:this.onSelectPage
				};
				this.grid=$('#'+options.grid_id);
				var isPagination=true;
				//if(options.pager_id){
					//this.grid.pager=$('#'+options.pager_id);
					//this.grid.pager.pagination(this.paginationOptions);
				this.grid.gridParam={};
				if(options.paging=="no"){
					//不分页
					this.grid.gridParam.paging="no";
					isPagination=false;
				}else{
					this.grid.gridParam.pageNumber=1;
					this.grid.pageSize=this.paginationOptions.pageSize;
				}
				if(options.gridParam){
					$.extend(this.grid.gridParam,options.gridParam);
				}
				this.grid.searchParamOperator=options.searchParamOperator;
				//}
				
				this.gridOptions={
						idField:'id',//指定id字段
						sqlname:options.sqlname,
						toolbar:"#searchbar",
						fit:true,
					    singleSelect: true,//单选
						rownumbers:true,//显示序号
						pagination:isPagination,//显示分页
						columns:this.columns,//定义显示列
						onSortColumn:this.onSortColumn,//点击排序按钮触发函数
						onClickRow:function(rowIndex, rowData){
							//单击事件
							if(options.onClickRow){
								options.onClickRow(rowIndex, rowData);
							}
						},
						onDblClickRow:this.onDblClickRow,//双击行触发函数
						//selectOnCheck:false,//点击复选框是否选中该行
						//checkOnSelect:false,//点击行时是否选中复选框
						multiSort:true,//是否启用多列排序
						nowrap:true,
				};
				if(options.isToolbar=="no"){
					delete this.gridOptions.toolbar;
				}else{
					if(options.toolbar_id){
						this.gridOptions.toolbar="#"+options.toolbar_id;
					}
				}
				if(options.rownumbers!=undefined){
					this.gridOptions.rownumbers=options.rownumbers;
				}
				if(options.singleSelect!=undefined){
					this.gridOptions.singleSelect=options.singleSelect;
				}
				if(options.rowedit!=undefined&&!options.rowedit){
					delete this.gridOptions.onDblClickRow;
				}
				if(options.idField!=undefined){
					this.gridOptions.idField=options.idField;
				}
				
				if(options.onLoadSuccess){
					this.gridOptions.onLoadSuccess=options.onLoadSuccess;
				}
				if(options.afterEditing){
					this.gridOptions.afterEditing=options.afterEditing;
				}
				this.gridOptions.loadurl=options.loadurl||("/authenticated/grid/"+options.sqlname);
				this.gridOptions.saveurl=options.saveurl||("/authenticated/grid/update/"+options.sqlname);
				this.initColumnUrl=options.initColumnUrl||"/authenticated/grid/column/v2/"+options.page_id;
				this.initColumn=function(){
					$.ajax({
						type: "post",
						contentType:"application/json",
						async:false,
						url:self.initColumnUrl,
						success:function(result){
							if(result.success){
								var gridColumn=result.data.column;
								if(gridColumn){
									self.comboboxDatas=result.data.combo_data;
									$.each(gridColumn,function(i,v){
										var column_name=v.column_name;
										//console.log(column_name);
										//console.log(self.gridOptions.idField);
										//var idField=dg.datagrid('options').idField;
										var column={field:column_name,title:v.column_display_name};
//										if(column_name==self.gridOptions.idField){
//											column.formatter=function(value,row,index){
//							            	    return value.toString();
//										  	}
//										}
										if(v.is_hidden=="yes"){
											column.hidden=true;
										}
										if(v.is_order=="yes"){
											column.sortable=true;
										}
										var edit_type=v.edit_column_type;
										if(edit_type=="combobox"){
											column.formatter=new self.fun.field.formatter(column_name).comboboxFormatter;
											if(v.is_edit_column=="yes"){
												column.editor={
														type:'combobox',
														options:{
															panelHeight:'auto',
															panelMaxHeight:200,
															editable:false,
															valueField:'code_value',
															textField:'code_name',
															data: self.comboboxDatas[column_name]
														}
													};
											}
										}else if(edit_type=="combotree"){
											var newArray=transformCombotreeArray(self.comboboxDatas[column_name]);
											self.combotreeDatas[column_name]=newArray;
											column.formatter=new self.fun.field.formatter(column_name).combotreeFormatter;
											if(v.is_edit_column=="yes"){
												column.editor={
														type:'combotree',
														options:{
															data:newArray
														}
													};
											}
										}else if(edit_type=="datetimebox"){
											if(v.is_edit_column=="yes"){
												column.editor={
														type:'datetimebox',
														options:{
															//showSeconds:false
														}
													};
											}else{}
										}else if(edit_type=="datebox"){
											if(v.is_edit_column=="yes"){
												column.editor={
														type:'datebox',
														options:{
														}
													};
											}else{}
										}else if(edit_type=="image"){
											column.formatter=function(value,row,index){
							            	    if(value){
							            	    	return "<img style=\"height:100px;width:100px;\"  src=\""+value+"\" />";
							            	    }else{
							            	    	return "无图片";
							            	    }
										  	}
										}else if(edit_type=="integer"){
											if(v.is_edit_column=="yes"){
												column.editor={
														type:'numberbox',options:{}
													};
											}
										}else if(edit_type=="decimal"){
											if(v.is_edit_column=="yes"){
												column.editor={
														type:'numberbox',options:{precision:2}
													};
											}
										}else{
											if(v.is_edit_column=="yes"){
												column.editor={
														type:'textbox',options:{}
													};
											}
										}
										if(options.column_formatter&&options.column_formatter[column_name]){
											column.formatter=options.column_formatter[column_name];
										}
										if(v.width&&v.width>0){
											column.width=v.width;
										}
										self.columns[0].push(column);
									});
									
								}
							}else{
								$.messager.alert("提示", "初始化表格失败："+result.message);
							}
						}
					})
					
				}
				if(options.columns){
					this.columns=options.columns;
					this.gridOptions.columns=options.columns;
				}else{
					this.initColumn();
				}
				this.grid.datagrid(this.gridOptions);
				this.grid.pager=this.grid.datagrid('getPager');
				this.grid.pager.pagination(this.paginationOptions);
				if(options.autoload==undefined||options.autoload){
					this.grid.datagrid("load");
				}
				$(document).keydown(function(event){
					if(event.keyCode == 13){
						self.load();
					}
				});
			}
		}
};